<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="app">
      <h2>已完成的待办事项</h2>
      <ul>
        <li v-for="todo in doneTodos">{{todo.text}}</li>
      </ul>
      <p>已完成的待办事项的数量{{doneCount}}</p>
      <p>未完成的待办事项的数量{{undoneCount}}</p>
      <p>待办事项总数量{{totalCount}}</p>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script>
    <script src="https://unpkg.com/vuex@3.1.3/dist/vuex.js"></script>
    <script>
      var store = new Vuex.Store({
        state: {
          todos:[
            {id:1,text:'play basketball',done:true},
            {id:2,text:'play baseball',done:true},
            {id:3,text:'song',done:false}
          ]
        },
        getters:{//类似于仓库的计算属性，如果你有一些从仓库状态中派生或者说计算得到的属性，就可以封装getters
          doneTodos(state){
            return state.todos.filter(todo=>todo.done)
          },
          doneCount(state,getters){
            return getters.doneTodos.length;
          },
          undoneCount(state){
            return state.todos.filter(todo=>!todo.done).length;
          },
          totalCount(state,getters){
            return state.todos.length;
          }
        }
      });
      var vm = new Vue({
        store,
        el: "#app",
        computed:{
          doneTodos(){
            return this.$store.getters.doneTodos;
          },
          doneCount(){//组件不需要重复计算 2.可以实现缓存，如果状态不变，不需要重新计算，状态变了才需要重新计算
            return this.$store.getters.doneCount;
          },
          undoneCount(){
            return this.$store.getters.undoneCount;
          },
          totalCount(){
            return this.$store.getters.totalCount;
          }
        }
      });
    </script>
  </body>
</html>
